<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 * @author   howe <howe1995@163.com>
 */

namespace App\Middleware;

use App\Constant\ApiCodeEnum;
use App\Support\Traits\ServiceException;
use Exception;
use Fastknife\Service\BlockPuzzleCaptchaService;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

use function Hyperf\Config\config;

class CaptchaMiddleware implements MiddlewareInterface
{
    use ServiceException;

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $captchaVerification = $request->getParsedBody()['captchaVerification'] ?? '';
        if (empty($captchaVerification)) {
            $this->throwBusinessException(ApiCodeEnum::SERVICE_CODE_ERROR);
        }
        // 滑块验证
        $captchaService = new BlockPuzzleCaptchaService(config('captcha'));
        try {
            $captchaService->verificationByEncryptCode($captchaVerification);
        } catch (Exception $e) {
            $this->throwBusinessException(ApiCodeEnum::SYSTEM_ERROR, $e->getMessage());
        }
        return $handler->handle($request);
    }
}
